﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Inaction.DbSchame
{
    [Serializable]
    [DisplayName("表的定义")]
    public class Table : NameObject, ITable
    {
        #region 构造
        public Table()
        {
            Columns = new List<Column>();
            ForeignKeys = new List<ForeignKey>();
            UniqueKeys = new List<UniqueKey>();
            ForeignKeyChildren = new List<Table>();
        }
        #endregion

        #region 属性
        Column primaryKey = null;
        [DisplayName("主键列")]
        public Column PrimaryKey
        {
            get
            {
                if (primaryKey == null)
                    primaryKey = Columns.FirstOrDefault(p => p.IsPrimaryKey);
                return primaryKey;
            }
        }
        [DisplayName("列集合")]
        public List<Column> Columns { get; private set; }
        [DisplayName("外键集合")]
        public List<ForeignKey> ForeignKeys { get; internal set; }
        [DisplayName("惟一索引集合")]
        public List<UniqueKey> UniqueKeys { get; internal set; }
        [DisplayName("参照此表的所有外键子表")]
        public List<Table> ForeignKeyChildren { get; internal set; }

        #endregion

        public string CreareSelectSql()
        {
            var orderCoumns = Columns.OrderBy(p => p.Ordinal);
            return "Select " + string.Join(",", orderCoumns.Select(p => p.FormatName)) + Environment.NewLine + " From " + FormatName;
        }

        public string CreateInsertSql()
        {
            var orderCoumns = Columns.OrderBy(p => p.Ordinal);
            return "Insert Into " + Name + " (" + string.Join(",", orderCoumns.Select(p => p.FormatName)) + ")" + Environment.NewLine
                + " Values (" + string.Join(",", orderCoumns.Select(p => Inaction.DbProvider.Instance.ParaFix + p.Name)) + ")";
        }

        public string CreateUpdateSql()
        {
            var orderCoumns = Columns.OrderBy(p => p.Ordinal);
            return "Update " + FormatName + Environment.NewLine
                + " Set " + string.Join(",", orderCoumns.Select(p => p.FormatName + " = " + Inaction.DbProvider.Instance.ParaFix + p.Name)) + Environment.NewLine
            + " Where " + PrimaryKey.Name + " = " + Inaction.DbProvider.Instance.ParaFix + PrimaryKey.Name;
        }

        public string CreateDeleteSql()
        {
            return "Delete From " + FormatName + " " + " Where " + PrimaryKey.Name + " = " + Inaction.DbProvider.Instance.ParaFix + PrimaryKey.Name;
        }
    }
}
